import Dep from "./Dep";

var uid = 0;
export default class Watcher {
    constructor(target, expression, callback) {
        this.id = uid++;
        this.target = target;
        this.gettr = parsePath(expression);//'a.b.c.d'
        this.callback = callback;
        this.value = this.get();
    }
    update() {
        this.getAndInvoke(this.callback);
    }
    get() {
        //进入依赖收集阶段，让全局的Dep,target设置为watcher本身，那么就是进入依赖收集阶段
        Dep.target = this;
        const obj = this.target;
        var value;
        try {
            value = this.gettr(obj);
        } finally {
            //收集完毕，退出，其他watcher需要
            Dep.target = null;
        }
        return value;
    }
    //获取数据并更新
    getAndInvoke(cb) {
        const value = this.get();
        if (value !== this.value || typeof value == 'object') {
            const oldValue = this.value;
            this.value = value;
            cb.call(this.target, value, oldValue);
        }
    }
};
function parsePath(str) {
    //作用是：把'a.b.c.d'这种转换成a{b:{c:{d:{}}}}
    var segments = str.split('.');
    return (obj) => {
        for (let i = 0; i < segments.length; i++) {
            if (!obj) {
                return;
            }
            obj = obj[segments[i]];
        }
        return obj;
    }
}